<?php

namespace App\Console\Commands;

use App\Console\Base;
use App\Models\HallConfig;
use common\enum\CommonEnum;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class HallMaintain extends Base
{
    /**
     * 控制台命令 signature 的名称。
     *
     * @var string
     */
    protected $signature = self::PREFIX . 'hallmaintain {--hall_id=}';

    /**
     * 控制台命令说明。
     *
     * @var string
     */
    protected $description = 'HallMaintain';

    /**
     * 执行控制台命令。
     *
     * @return mixed
     */
    public function handle()
    {
        $time = time();
        $configObj = HallConfig::whereIn('status', [CommonEnum::STATUS_ENABLED, CommonEnum::STATUS_FREEZE, CommonEnum::STATUS_MAINTAINING]);
        $hallData  = $configObj->get();
        if (!$hallData) {
            Log::info('$hallData null');
            return true;
        }
        $hallData = $hallData->toArray();
        foreach ($hallData as $key => $value) {
            Log::info('hallmaintain-old' . 'hall_id' . $value['hall_id'] . $value['start_time'] . '-' . $value['end_time'] . '|' . $value['status']);
            if (strtotime($value['start_time']) <= $time && $time < strtotime($value['end_time'])) {
                if ($value['status'] != CommonEnum::STATUS_MAINTAINING) {
                    // 维护开启，备份配置
                    $configObj->where(['hall_id' => $value['hall_id']])->update(['pre_status' => DB::raw('status')]);
                    $configObj->where(['hall_id' => $value['hall_id']])->update(['status' => CommonEnum::STATUS_MAINTAINING]);
                }
            } else {
                if ($value['status'] == CommonEnum::STATUS_MAINTAINING) {
                    // 维护完成，还原配置
                    $configObj->where(['hall_id' => $value['hall_id']])->update(['status' => DB::raw('pre_status')]);
                }
            }
            Log::info('hallmaintain-new' . 'hall_id' . $value['hall_id'] . $value['start_time'] . '-' . $value['end_time'] . '|' . $value['status']);
        }
    }
}
